package com.eaglefly.redis.core;

import com.eaglefly.redis.utils.RedissonUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.Codec;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 代理类
 *
 * @author zhaojinpeng
 */
public class DaoProxy<I, S> implements InvocationHandler, Serializable {

    /**
     * redisson
     */
    private RedissonClient redisson;
    /**
     * 接口的类型
     */
    private final Class<I> daoInterface;
    /**
     * 接口的父级接口类型
     */
    private final Class<S> supperInterface;

    private Object subject;

    /**
     * @param redisson
     * @param daoInterface    接口类型
     * @param supperInterface 父级接口类型
     * @param redisKey        redis对应的key值
     * @param codec           序列化方式
     */
    public DaoProxy(Redisson redisson, Class<I> daoInterface, Class<S> supperInterface, String redisKey, Codec codec) {
        this.redisson = redisson;
        this.daoInterface = daoInterface;
        this.supperInterface = supperInterface;
        this.subject = RedissonUtils.getRedisObject(redisson, supperInterface, redisKey, codec);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //判断是不是基础方法 比如toString() hashCode()等，这些方法直接调用不需要处理
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(proxy, args);
        }
        //调用实际实现类
        return method.invoke(subject, args);
    }
}
